//
//  BookTagColCell.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/13.
//

import UIKit

class BookTagColCell: UICollectionViewCell, UIScrollViewDelegate {
    
    lazy var tagLabel: UILabel = {
        let label = UILabel()
        label.text = "TAGS"
        label.font = .wn_font(name: .bold, size: 16)
        label.textColor = .black
        return label
    }()
    
    lazy var scrollView: UIScrollView = {
        let scro = UIScrollView.init(frame: .zero)
        scro.showsHorizontalScrollIndicator = false
        scro.showsVerticalScrollIndicator = false
        scro.delegate = self
        return scro
    }()
    
    var tagViewArr = [UIButton]()
    
    var tagArr = [TagsModel]() {
        didSet {
            for item in scrollView.subviews {
                item.removeFromSuperview()
            }
            tagViewArr.removeAll()
            var contentW: CGFloat = 0.0
            isHidden = tagArr.count == 0
            guard tagArr.count > 0 else { return }
            for i in 0..<tagArr.count {
                let btn = UIButton(type: .custom)
                btn.setTitle(tagArr[i].label_name, for: .normal)
                btn.setTitleColor(.black, for: .normal)
                btn.titleLabel?.font = .wn_font(name: .bold, size: 12)
                btn.titleLabel?.textAlignment = .center
                btn.backgroundColor = .white
                btn.rx.tap.bind { [weak self] in
                    self?.viewContainingController?.wn_pushTypeBookVC(self?.tagArr[i])
                }.disposed(by: rx.disposeBag)
                var width = wn_getTextW(textStr: tagArr[i].label_name ?? "", font: .wn_font(name: .bold, size: 12), height: 12)+20
                width = width < 40 ? 40 : width
                btn.frame = CGRect(x: contentW, y: 0, width: width, height: 32)
                btn.wn_cornerWithBorder(16)
                width += 10
                contentW += width
                scrollView.addSubview(btn)
                tagViewArr.append(btn)
            }
            scrollView.contentSize = CGSize(width: contentW, height: 0)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .init(named: "white_FBF6F1")
        addSubview(tagLabel)
        addSubview(scrollView)
        tagLabel.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(12)
        }
        scrollView.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.left.equalTo(tagLabel.snp.right).offset(12)
            make.right.equalTo(0)
            make.height.equalTo(32)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
